package com.opengroupe.recognize;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
/**
 * Activity responsable sur l'affichage des résultats de recherche.
 * @author HAM11235
 *
 */
public class DisplayingResultActivity extends Activity {

	/** l'identifiant du fichier sur google drive. */
	public String idFile;
	
	/** le résultat du traitemetn ocr.*/
	public String ocr;
	
	/** les mots clés utilisé pour la recherche. */
	public String keyWords;
	
	/**
	 * Création de l'activité et récupération des params passé à l'activité.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.display_result_activity_layout);
		initLayout();
		Bundle extras = getIntent().getExtras(); 
		idFile = extras.getString("idFile");
		ocr = extras.getString("ocr");
		keyWords = extras.getString("keyWords");
	}

	/**
	 * cache les objets de la page le temps de charger le résultat de recherche.
	 */
	private void initLayout() {
		((Button)findViewById(R.id.Button01)).setVisibility(View.INVISIBLE);
		((Button)findViewById(R.id.Button02)).setVisibility(View.INVISIBLE);
		((Button)findViewById(R.id.Button03)).setVisibility(View.INVISIBLE);
		((Button)findViewById(R.id.Button04)).setVisibility(View.INVISIBLE);
		((Button)findViewById(R.id.Button05)).setVisibility(View.INVISIBLE);
		((TextView)findViewById(R.id.textView1)).setVisibility(View.INVISIBLE);
	}

	/**
	 * Mise à jour de l'entête du résultat de recherche.
	 * @param nb
	 */
	public void updateEntete(int nb) {
		final int nbFile = nb;
		runOnUiThread(new Runnable() {  
			@Override
			public void run() {
				// textView1
				TextView enteteView = (TextView) findViewById(R.id.textView1);
				enteteView.setVisibility(View.VISIBLE);
				enteteView.setText("Number of file found: " + nbFile);//R.string.nbfilefound + " " + nbFile);
			}
		});
	}
	
	/**
	 * Chargement du fichier à partir du drive et affectation de l'action sur le clic du bouton.
	 * @param button1
	 * @param fileFromDrive
	 */
	private void getFileAndUpdateButtonListener(Button button, File fileFromDrive) {
		final Button btn = button;
		final File file = fileFromDrive;
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				InputStream is = Utility.downloadFile(file);
				OutputStream outputStream = null;
				java.io.File tmpFile = null;
				try {
					Log.i("recognize", "repertoire résultat: " + Const.resultSearchFolder);
					
					//creation du réperoire resultSearchFolder dans le cas où il n'exste pas.
					java.io.File resultSearchDir = new java.io.File(Const.resultSearchFolder);
					if(!resultSearchDir.exists()) {
						resultSearchDir.mkdirs();
					}
					tmpFile = new java.io.File(Const.resultSearchFolder + java.io.File.separator + file.getTitle());
					outputStream =  new FileOutputStream(tmpFile);
					int read = 0;
					byte[] bytes = new byte[1024];
					while ((read = is.read(bytes)) != -1) {
						outputStream.write(bytes, 0, read);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				final java.io.File fileToDisplay = tmpFile;
				btn.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Uri path = Uri.fromFile(fileToDisplay);
						Intent intent = new Intent(Intent.ACTION_VIEW);
						if(Const.PDF.equals(file.getFileExtension())){
							intent.setDataAndType(path, Const.APPLICATION_PDF);
						} else if(Const.PNG.equals(file.getFileExtension()) || Const.JPG.equals(file.getFileExtension())) {
							intent.setDataAndType(path, Const.APPLICATION_IMAGE);
						} else if(Const.MP4.equals(file.getFileExtension())) {
							intent.setDataAndType(path, Const.APPLICATION_VIDEO);
						} else {
							Toast.makeText(getApplicationContext(), "Can not read the file: " + file.getOriginalFilename(), Toast.LENGTH_LONG).show();
						}
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						try {
							startActivity(intent);
						} catch (ActivityNotFoundException e) {
							Toast.makeText(getApplicationContext(), "Can not read the file: " + file.getOriginalFilename(), Toast.LENGTH_LONG).show();
							Log.e("recognizer", e.toString());
						}
					}
				});
			}
		});
		t.start();
	}

	/**
	 * Maximum du résultat de recherche: 5.
	 * @param index
	 * @param fileDrive
	 */
	public void updateLayOutForResult(int index, com.google.api.services.drive.model.File fileDrive){
		
		final int i = index + 1;
		final String fileTitle = fileDrive.getTitle();
		final com.google.api.services.drive.model.File file = fileDrive;
		cleanResultSearchFolder(Const.resultSearchFolder);
		runOnUiThread(new Runnable() {  
			@Override
			public void run() {
				if(i == 1){
					//Activation du bouton 1
					Button button1 = (Button) findViewById(R.id.Button01);
					button1.setVisibility(View.VISIBLE);
					button1.setText(fileTitle);
					button1.refreshDrawableState();
					getFileAndUpdateButtonListener(button1, file);
					
				} else if(i == 2){
					//Activation du bouton 2
					Button button2 = (Button)findViewById(R.id.Button02);
					button2.setVisibility(View.VISIBLE);
					button2.setText(fileTitle);
					button2.refreshDrawableState();
					getFileAndUpdateButtonListener(button2, file);
				} else if(i == 3){
					//Activation du bouton 3
					Button button3 = (Button)findViewById(R.id.Button03);
					button3.setVisibility(View.VISIBLE);
					button3.setText(fileTitle);
					button3.refreshDrawableState();
					getFileAndUpdateButtonListener(button3, file);
				} else if(i == 4){
					//Activation du bouton 4
					Button button4 = (Button)findViewById(R.id.Button04);
					button4.setVisibility(View.VISIBLE);
					button4.setText(fileTitle);
					button4.refreshDrawableState();
					getFileAndUpdateButtonListener(button4, file);
				} else if(i == 5){
					//Activation du bouton 5
					Button button5 = (Button)findViewById(R.id.Button05);
					button5.setVisibility(View.VISIBLE);
					button5.setText(fileTitle);
					button5.refreshDrawableState();
					getFileAndUpdateButtonListener(button5, file);
				} 
			}
		});
	}

	/**
	 * suppression des fichiers issue de la recherche précédente.
	 * @param resultSearchFolder
	 */
	private void cleanResultSearchFolder(String resultSearchFolder) {
		java.io.File folder = new java.io.File(resultSearchFolder);
		if(folder.exists()){
			if(folder.isDirectory()){
				String[] fileNames = folder.list();
				if(fileNames.length != 0) {
					//suppression des fichiers résultat de l'ancienne recherche.
					for(String fileName : fileNames) {
						Log.i("recognizer: ", "fileName to delete: " + fileName);
						(new java.io.File(resultSearchFolder + java.io.File.separator + fileName)).delete();
						(new java.io.File(resultSearchFolder + java.io.File.separator + fileName)).deleteOnExit();
					}
				}
			}
		}
	}

	/**
	 * Démarrage de la recherche.
	 * @param keyWords
	 */
	private void startSearchingOnrive(String keyWords, String ocrWords) {
		final String word = keyWords;
		final String ocr = ocrWords;
		(new Thread(){
			@Override
			public void run() {
				Drive drive = MainActivity.getService();
				FileList files = null;
				try {
					files = drive.files().list()
							.setQ("fullText contains '" + (!Utility.estVide(ocr)?ocr:word) + "'")
							.setMaxResults(5).execute();
					List<com.google.api.services.drive.model.File> result = new ArrayList<File>();
					result.addAll(files.getItems());
					int nbResult = 0;
					for(File file : result){
						if(file.getFileExtension() != null && !Utility.estVide(file.getFileExtension()))
							nbResult ++;
					}
					if(result.size() != 0) {
						updateEntete(nbResult);
						int compteur = 0;
						for(int i = 0; i<result.size(); i++) {
							com.google.api.services.drive.model.File file = result.get(i);
							// ici on ne traite pas les fichiers qui n'ont pas d'extension et les dossier aussi.
							if(file.getFileExtension() != null && !Utility.estVide(file.getFileExtension())){
								updateLayOutForResult(compteur ++, file);
							}
							Log.i("recognize", "file.getId(): " + file.getId());
							Log.i("recognize", "file.getTitle(): " + file.getTitle());
							Log.i("recognize", "file.getEtag(): " + file.getEtag());
							Log.i("recognize", "file.getMimeType(): " + file.getMimeType());
							Log.i("recognize", "file.getOriginalFilename(): " + file.getOriginalFilename());
							Log.i("recognize", "file.getFileSize(): " + file.getFileSize());
							Log.i("recognize", "file.getFileExtension(): " + file.getFileExtension());
							Log.i("recognize", "file.getDescription(): " + file.getImageMediaMetadata());
							Log.i("recognize", "file.getUserPermission(): " + file.getUserPermission());
						}
					} else {
						updateEntete(0);
						
					}

				} catch (IOException e) {
					e.printStackTrace();
				}	
			}
		}).start();
	}

	/**
	 * Démarrage de l'activité.
	 */
	@Override
	protected void onStart() {
		super.onStart();
		startSearchingOnrive(keyWords, ocr);
	}

	/**
	 * Arret de l'activité.
	 */
	@Override
	protected void onStop() {
		super.onStop();
	}

}
